package com.totoro.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by Niki on 2018/4/12 19:36
 */
public class SimpleNIOClient {
    private static void client() {
        SocketChannel channel = null;
        try {
            channel = SocketChannel.open();
            channel.connect(new InetSocketAddress("127.0.0.1", 9999));
            String msg = "总部，我是client！";
            ByteBuffer buffer = ByteBuffer.allocate(msg.getBytes().length);
            buffer.clear();
            buffer.put(msg.getBytes());
            buffer.flip();
            while (buffer.hasRemaining()) {
                channel.write(buffer);
            }

            ByteBuffer receiveBuff = ByteBuffer.allocate(512);

            channel.read(receiveBuff);

            System.out.println("收到服务端消息：" + new String(receiveBuff.array(), "utf-8"));

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        client();
    }
}
